package group1;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.testng.*;
import org.testng.annotations.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Rzhd1 extends group1.pages.TestBase {
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @Test
  public void testRzhd1() throws Exception {
    driver.get("http://rzd.ru/");
    driver.findElement(By.id("name0")).clear();
    driver.findElement(By.id("name0")).sendKeys("СА");
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if ("САНКТ-ПЕТЕРБУРГ".equals(driver.findElement(By.cssSelector("div.station")).getText())) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }

    driver.findElement(By.cssSelector("div.station")).click();
    driver.findElement(By.id("name1")).clear();
    driver.findElement(By.id("name1")).sendKeys("ив");
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if ("ИВАНОВО ГОРОД".equals(driver.findElement(By.xpath("//div[7]/div")).getText())) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }

    driver.findElement(By.xpath("//div[7]/div")).click();
    driver.findElement(By.id("buttonDate")).click();
    driver.findElement(By.xpath("//div[@id='popup_calendar']/div/div/div/div[2]/div/ul/li[18]/span")).click();
    driver.findElement(By.id("Submit")).click();
    driver.findElement(By.id("continueButton")).click();
    assertEquals("Поезда НЕ выбраны", closeAlertAndGetItsText());
    driver.navigate().refresh();
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }
  
   public boolean isAlertPresent() {
  try {
    driver.switchTo().alert();
    return true;
  } catch (Exception ex) {
  }
  return false;
}

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}
